package com.wryyyyy.utils;

import com.wryyyyy.dto.UserDTO;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// 管理员权限
public class AdminInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 获取请求方式（GET或POST）
        String method = request.getMethod();
        // 获取请求路径
        String path = request.getRequestURI();
        String s = path.split("/", 0)[1];
        // 根据请求方式+路径判断是否放行
//        if (method.equals("GET") && (s.equals("dish") || s.equals("material") || s.equals("label"))) {
//            return true;
//        }

        // 1.判断是否要拦截（threadlocal中是否有用户）
        UserDTO userDTO = UserHolder.getUser();

        System.out.println(method + "---" +path + "---" + s);
        System.out.println(userDTO);

        if (userDTO == null) {
            response.setStatus(401);
            return false;
        } else if (!userDTO.getStanding()) {
            response.setStatus(401);
            return false;
        }
        return true;
    }

    @Override //校验完之后，销毁用户信息避免内存泄漏
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        //移除用户
        UserHolder.removeUser();
    }
}